package com.tegistuff.webos.run.debugger;

import com.intellij.xdebugger.frame.XExecutionStack;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * WebOSExecutionStack.java
 *
 * Copyright (C) 2011-2012 Timo Tegtmeier.
 * All rights reserved.
 */
public class WebOSExecutionStack extends XExecutionStack {

    private List<WebOSStackFrame> myFrames = new ArrayList<WebOSStackFrame>();
    private WebOSStackFrame myTopFrame = null;

    public WebOSExecutionStack(WebOSDebugProcess debugProcess, JSONObject frameInfo) {
        super("");

        try {
            JSONArray frames = frameInfo.getJSONArray("frames");
            for(int i = 0; i < frames.length(); i++) {
                WebOSStackFrame frame = new WebOSStackFrame(debugProcess, frames.getJSONObject(i));
                myFrames.add(frame);
                if(i == 0)
                    myTopFrame = frame;
            }
        }  catch (Exception e) {
            myFrames.clear();
            myTopFrame = null;
        }
    }

    public WebOSStackFrame getTopFrame() {
        return myTopFrame;
    }

    public void computeStackFrames(final int frameCount, final XStackFrameContainer container) {
        if (frameCount <= myFrames.size()) {
            container.addStackFrames(myFrames.subList(frameCount, myFrames.size()), true);
        } else {
            container.errorOccurred("No stack frames available");
        }
    }
}
